#include		<iostream>
#include		"RequestParser.hpp"
#include	 	"traitThread.hpp"
#include		"Request.h"
#include		"ZiaServerWin.h"
#include		"../Api Headers/DataTree.hpp"
#include		"ManipList.hpp"
#include		"Request.h"
#include		"tools.hpp"
#include		<utility>
#include		<fstream>

using namespace	std;

extern ManipList<pair<std::string, int> >		msgList;

void							*TraitLoop(void *useless)
{
	const pair<string, int>		*msg = NULL;
	cout << "test" << endl;

	while (1)
	{
		msg = msgList.takeMessage();
		if (msg != NULL)
		{
			cout << "Ca c'est batard" << endl;
			zia::api::DataTree		headerRequest, headerAnswer;
			RequestParser			Parser;
			Request					traitRequest;
			std::string				body;
//			std::string				*msg;

		
			cout << "Message --- : " << msg->first << endl;
			Parser.ParseRequest((msg->first), headerRequest, body);
			if (headerRequest["Method"] == "GET")
			{
				std::cout <<  "Him Here" << std::endl;
				body = traitRequest.traitGET(headerRequest["URL"], headerAnswer);
				headerAnswer.print(std::cout);
			}
			cout << "TEST WAIT" << endl;
			
			std::string	maRep;

			maRep += headerAnswer["version"];
			maRep += " ";
			maRep += headerAnswer["code"];
			maRep += " ";
			maRep += headerAnswer["msg"];
			maRep += "\r\n";
			//Date
			maRep += "Date : ";
			maRep += headerAnswer["date"];
			maRep += "\r\n";
			//ServerType
			maRep += "Server : ";
			maRep += headerAnswer["server"];
			maRep += "\r\n";
			//Contenu
			maRep += "Content-Type : ";
			maRep += headerAnswer["type"];
			maRep += "\r\n";
			//Taille
			maRep += "Content-Length : ";
			maRep += headerAnswer["length"];
			maRep += "\r\n";

			std::cout << "-------------------------" << std::endl;
			std::cout << maRep << std::endl;
			std::cout << "-------------------------" << std::endl;
			maRep += body;
			maRep += "\r\n\0";

			send(msg->second, maRep.c_str(), maRep.size(), 0);
			std::cout << "Sended" << std::endl;
			closesocket(msg->second);
			std::cout << "Closed" << std::endl;
			delete msg;
		}
		::tools::Sleep(1);
	}
	return (NULL);
}